package com.wise.site.push;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import com.wise.site.R;
import com.wise.site.main.IndexerActivity;
import com.wise.site.main.MainIndexActivity;
import com.wise.site.main.MoreActivity;
import com.wise.site.more.MorePush;
import com.wise.site.protocol.base.ProtocolManager;
import com.wise.site.protocol.base.SoapAction;
import com.wise.site.protocol.base.SoapAction.ACTION_TYPE;
import com.wise.site.protocol.base.SoapAction.ActionListener;
import com.wise.site.utils.Constanct;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.IBinder;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.text.format.DateFormat;
import android.util.Log;

public class PushService extends Service {
	private Timer timer = new Timer();
	private NotificationManager nm;
	private String androidId;
	private int error = 0;
	private boolean isDevicebook = false;
	public static boolean HAVINGNEW = false;
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			
			if(ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){
	            boolean success = false;

	            //获得网络连接服务
	            ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
	            // State state = connManager.getActiveNetworkInfo().getState();
	            State state = connManager.getNetworkInfo(
	                    ConnectivityManager.TYPE_WIFI).getState(); // 获取网络连接状态
	            if (State.CONNECTED == state) { // 判断是否正在使用WIFI网络
	                success = true;
	            }
	            
	            state = connManager.getNetworkInfo(
	                    ConnectivityManager.TYPE_MOBILE).getState(); // 获取网络连接状态
	            if (State.CONNECTED != state) { // 判断是否正在使用GPRS网络
	                success = true;
	            }
	            
	            if(success && !isDevicebook){
	            	devieUUID();
	            }
			} else {
				HAVINGNEW = false;
				sendBroadcast(new Intent(MoreActivity.PUSH_NEW_ACTION));
				Intent i = new Intent(getApplicationContext(), MorePush.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(i);
			}
		}
	};

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		androidId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		IntentFilter filter = new IntentFilter(PushService.class.getName());
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mReceiver, filter);
		
		nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		devieUUID();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				if(!isDevicebook){
					devieUUID();
				}
				downloadData();
			}
		}, 15000, Constanct.PUSH_TIME);
	}

	private void devieUUID() {
		SoapAction<Integer> action = new SoapAction<Integer>(
				ACTION_TYPE.ACTION_COMMON, "devicebook") {
			@Override
			protected Integer parseJson(String response) throws Exception {
				JSONObject json = new JSONObject(response);
				int flag = 0;
				if(!json.isNull("flag")){
					flag = json.getInt("flag");
				}
				isDevicebook = true;
				return flag;
			}
		};
		action.addJsonParam("UUID", androidId);
		action.addJsonParam("PhoneType", 1);
		action.addJsonParam("menhuID", Constanct.INDUSTRY_ID);
		action.addJsonParam("IP", "");
		action.addJsonParam("times",
		DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date()));
		action.setActionListener(new ActionListener<Integer>() {
			public void onSucceed(Integer result) {
			}
			public void onError(int resultCode) {
				if(error < 3){
					error++;
					devieUUID();
				} else {
					error = 0;
				}
			}
		});
		
		
		ProtocolManager.getProtocolManager().submitAction(action);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		try{
			unregisterReceiver(mReceiver);
			timer.cancel();
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private void downloadData() {
		SoapAction<Integer> sAction = new SoapAction<Integer>(
				ACTION_TYPE.ACTION_COMMON, "msg_getmsg") {
			@Override
			protected Integer parseJson(String response)
					throws Exception {
				JSONObject json = new JSONObject(response);
				int flag = 0;
				if(!json.isNull("flag")){
					flag = json.getInt("flag");
					JSONArray array = new JSONArray(json.getString("msg"));
					if(flag == 1 && array.length() > 0) {
						for(int i = 0; i < array.length(); i++){
							json = array.getJSONObject(i);
							if(!json.isNull("isRead")){
								if(json.getInt("isRead") == 0){
									Notification notify = new Notification(R.drawable.ic_launcher, getResources().getString(R.string.app_name), System.currentTimeMillis());
									
									Intent intent = new Intent(PushService.class.getName());
									notify.setLatestEventInfo(getApplicationContext(), getString(R.string.app_name), json.getString("content"), PendingIntent.getBroadcast(PushService.this, 0, intent,
											PendingIntent.FLAG_CANCEL_CURRENT));
									notify.defaults |= Notification.DEFAULT_SOUND; 
									notify.flags|=Notification.FLAG_AUTO_CANCEL; 
									nm.notify(R.string.app_name, notify);
									HAVINGNEW = true;
									sendBroadcast(new Intent(MoreActivity.PUSH_NEW_ACTION));
									break;
								}
							}
						}
					}
				}
				return flag;
			}
		};
		sAction.setActionListener(new ActionListener<Integer>() {
			public void onSucceed(Integer result) {
			}
			public void onError(int resultCode) {
				if(error < 3){
					error++;
					downloadData();
				} else {
					error = 0;
				}
			}
		});
		sAction.addJsonParam("AccountID", Constanct.INDUSTRY_ID + "");
		sAction.addJsonParam("UUID", androidId);
		sAction.addJsonParam("PhoneType", 1);
		sAction.addJsonParam("IP", "");

		ProtocolManager.getProtocolManager().submitAction(sAction);
	}
	

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}
